/*
 * Copyright (c) 2016-2021, Hangzhou Qulian Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "log.h"
// -----------------------
// Log Config
// -----------------------
static struct {
    OhLongLevel   level;
    OhBoolType    quiet;
} L;
OhVoidType LogSetLevel(OhLongLevel level) {
    L.level = level;
}
OhVoidType LogSetQuiet(OhBoolType enable) {
    L.quiet = enable;
}

// -----------------------
// Log Callback Handle
// -----------------------
PrintLogCallback printHandle = NULL;
OhVoidType SetPrintLogCallback(PrintLogCallback callback){
    printHandle = callback;
}
GetTimeCallback getTimeHandle = NULL;
OhVoidType SetGetTimeCallback(GetTimeCallback callback){
    getTimeHandle = callback;
}

// -----------------------
// Log Output
// -----------------------
static const char *levelStrings[] = {
 "DEBUG", "INFO", "WARN", "ERROR"
};

#ifdef LOG_USE_COLOR
static const char *levelColors[] = {
  "\x1b[36m", "\x1b[32m", "\x1b[33m", "\x1b[31m"
};
#endif

static char logTitle[160];
static char logDetail[LOG_MAX_SIZE];

OhVoidType Logs(OhLongLevel l, const char *file, int line, const char *fmt, ...) {

    va_list ap;
    // param type convert
    int level = (int)l;
    // Get Time
#ifdef LOG_USE_TITLE
    char timeBuf[16] = {'\0'};
    if(getTimeHandle){
        getTimeHandle(timeBuf, 16);
    }
#endif
    // Format
    if (!L.quiet && level >= L.level) {
        memset(logTitle,  0, 160);
        memset(logDetail, 0, LOG_MAX_SIZE);
#ifdef LOG_USE_TITLE
  #ifdef LOG_USE_COLOR
        sprintf( logTitle, "%s %s%-5s\x1b[0m \x1b[90m%s:%d:\x1b[0m ",
                 timeBuf, levelColors[level], levelStrings[level], file, line);
  #else
        sprintf( logTitle, "%s %-5s %s:%d: ",
                 timeBuf, levelStrings[level], file, line);
  #endif
#endif
        // Get Param
        va_start(ap, fmt);
        vsnprintf( logDetail, sizeof(logDetail), fmt, ap);
        va_end(ap);

        if(printHandle){
#ifdef LOG_USE_TITLE
            printHandle(logTitle);
#endif
            printHandle(logDetail);
            printHandle("\n");
        }
    }
}

